package mr.weblog.part1;

import mr.support.ConfHelper;
import mr.weblog.part1.WeblogReduceSideJoinReducer.ReduceSideGroupComparator;
import mr.weblog.part1.WeblogReduceSideJoinReducer.ReduceSidePartitioner;
import mr.weblog.support.TextPair;
import mr.weblog.support.WeblogHBaseSchema;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil;
import org.apache.hadoop.hbase.mapreduce.TableOutputFormat;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.MultipleInputs;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.LazyOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

public class WeblogReduceSideJoinJob extends Configured implements Tool{
    
    public int run(String[] args) throws Exception {
        Job job = Job.getInstance(getConf(), this.getClass().getName());        
        job.setJarByClass(getClass());
        
        Configuration jobConf = job.getConfiguration();
		ConfHelper confHelper = new ConfHelper(jobConf);
        
        MultipleInputs.addInputPath(job, confHelper.getInput(), TextInputFormat.class, WeblogMapper.class);
        MultipleInputs.addInputPath(job, confHelper.getInput2(), TextInputFormat.class, StockDataMapper.class);

        job.setReducerClass(WeblogReduceSideJoinReducer.class);
        job.setMapOutputKeyClass(TextPair.class);
        job.setMapOutputValueClass(TextPair.class);
        
        job.setOutputFormatClass(TableOutputFormat.class);
        jobConf.set(TableOutputFormat.OUTPUT_TABLE, WeblogHBaseSchema.ENHANCED_LOGS_TABLE);
        job.setOutputKeyClass(NullWritable.class);
        job.setOutputValueClass(Writable.class);   
        
        job.setPartitionerClass(ReduceSidePartitioner.class);
        job.setGroupingComparatorClass(ReduceSideGroupComparator.class);
        
        // this needs to happen at the end because it will setJarByClass for
        // various class configured on job such as OutputFormat
        TableMapReduceUtil.addDependencyJars(job);
        
        return job.waitForCompletion(true) ? 0 : 1;
    }

    public static void main(String[] args) throws Exception {
        int exitCode = ToolRunner.run(new WeblogReduceSideJoinJob(), args);
        System.exit(exitCode);
    }
}
